﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Yuchen.NPA.Core
{
    public class EntityMetaData
    {
        static EntityMetaData()
        {
            EntityTypes = AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic)
                .SelectMany(x => x.GetExportedTypes())
                .Where(x => x.IsInterface)
                .Where(x => !x.IsGenericType)
                .Select(GetEntityType)
                .Where(x => x != null)
                .ToList();

        }
        static Type GetEntityType(Type type)
        {
            var baseType = type.GetInterfaces().FirstOrDefault();
            if (baseType == null)
            {
                return null;
            }

            while (baseType.GetInterfaces().Length > 0)
            {
                baseType = baseType.GetInterfaces()[0];
            }

            if (!baseType.IsGenericType)
            {
                return null;
            }

            if (typeof(INpaRepository<,>) != baseType.GetGenericTypeDefinition())
            {
                return null;
            }

            var args = baseType.GetGenericArguments();
            EntityKeys.Add(args[0], args[1]);
            return args[0];
        }
        public static IEnumerable<Type> EntityTypes { get; } = new List<Type>();
        public static IDictionary<Type, Type> EntityKeys { get; } = new ConcurrentDictionary<Type, Type>();
    }
}
